/**
 * @Date 2025/3/13 13:31
 * @Created by 衡盛永
 */

package com.shangting.web.security;

import com.shangting.common.entity.Permission;
import com.shangting.common.entity.SystemUser;
import com.shangting.common.enums.BaseStatus;
import com.shangting.common.exception.ShangTingException;
import com.shangting.common.result.ResultCodeEnum;
import com.shangting.web.mapper.PermissionMapper;
import com.shangting.web.mapper.SystemUserMapper;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SystemUserMapper systemUserMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 校验用户是否存在
        SystemUser systemUser = systemUserMapper.selectOneByUsername(username);
        if (systemUser == null) {
            throw new ShangTingException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }

        // 校验用户是否被禁
        if (systemUser.getStatus() == BaseStatus.DISABLE) {
            throw new ShangTingException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }

        // 校验用户密码
        //if (!systemUser.getPassword().equals(DigestUtils.md5Hex(loginVo.getPassword()))) {
        //    throw new ShangTingException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        //}

        // 授权
        List<Permission> permissions = permissionMapper.getPermissionByUserId(systemUser.getId());
        ArrayList<String> authoritieStrList = new ArrayList<>();
        System.out.println("permission:" + permissions);
        if (!permissions.isEmpty()) {
            for (Permission permission : permissions) {
                authoritieStrList.add(permission.getUrl());
                authoritieStrList.add("ROLE_" + permission.getPostCode());
            }
        }

        return new UserDetailsImpl(systemUser, authoritieStrList);
    }
}
